<?php
namespace Order\Controller;
use Common\Controller\AdminbaseController;
use Common\Model\MemberModel;
use Common\Model\OrderModel;
use Common\Model\OrderProductModel;
use Common\Model\ProductModel;
use Common\Model\RefundModel;
use Common\Model\SystemMsgModel;
use Common\Model\UsersModel;

class OrderController extends AdminbaseController  {

    private $order_model;
    private $order_product_model;
    private $product_model;
    private $system_msg_model;
    private $region_model;
    private $member_model;
    private $users_model;
    private $refund_model;

    public function __construct(){
        parent::__construct();
        $this->order_model          = new OrderModel();
        $this->product_model        = new ProductModel();
        $this->system_msg_model     = new SystemMsgModel();
        $this->member_model         = new MemberModel();
        $this->order_product_model  = new OrderProductModel();
        $this->users_model          = new UsersModel();
        $this->refund_model         = new RefundModel();
    }

    public function lists() {
        $fields = [
            'order_sn'          => ["field" => "a.order_sn", "operator" => "like", 'datatype' => 'string'],
            'username'          => ["field" => "b.username", "operator" => "like", 'datatype' => 'string'],
        	'nickname'          => ["field" => "b.nickname", "operator" => "like", 'datatype' => 'string'],
            'status'            => ["field" => "a.status", "operator" => "=", 'datatype' => 'string'],
            'start_time'        => ["field" => "a.create_time", "operator" => ">=", 'datatype' => 'string'],
            'end_time'          => ["field" => "a.create_time", "operator" => "<=", 'datatype' => 'string'],
        	'pay_timeStart'     => ["field" => "a.pay_time", "operator" => ">=", 'datatype' => 'string'],
            'pay_timeEnd'       => ["field" => "a.pay_time", "operator" => "<=", 'datatype' => 'string'],
        ];

        $where_ands = [];
        if (IS_POST) {

            foreach ($fields as $param => $val) {
                if (isset($_POST[$param]) && !empty($_POST[$param])) {
                    $operator = $val['operator'];
                    $field = $val['field'];
                    $datatype = $val['datatype'];
                    $get = $_POST[$param];
                    $_GET[$param] = $get;

                    if ($operator == "like") {
                        $get = "%$get%";
                    }
                    if ($datatype == 'time')
                        $get = strtotime($get);
                        
                	if (($param=="end_time")||($param=="pay_timeEnd")) {
                    	$get.=" 23:59:59";
                    }    
                    array_push($where_ands, "$field $operator '$get'");
                }
            }
        } else {

            foreach ($fields as $param => $val) {
                if (isset($_GET[$param]) && !empty($_GET[$param])) {
                    $operator = $val['operator'];
                    $field = $val['field'];
                    $datatype = $val['datatype'];
                    $get = $_GET[$param];
                    if ($operator == "like") {
                        $get = "%$get%";
                    }
                    if ($datatype == 'time')
                        $get = strtotime($get);
                        
                    if (($param=="end_time")||($param=="pay_timeEnd")) {
                    	$get.=" 23:59:59";
                    }
                        
                    array_push($where_ands, "$field $operator '$get'");
                }
            }
        }
        //echo $param;
		//dump($where_ands);
		//exit;
        $where = join(" and ", $where_ands);

        $count = $this->order_model
            ->alias('a')
            ->join('INNER JOIN he_member as b ON a.mid = b.id')
            ->where($where)
            ->count();
        $page = $this->page($count, C('PAGE_NUMBER'));
        $ordersTotal = $this->order_model
            ->alias('a')
            ->join('INNER JOIN he_member as b ON a.mid = b.id')
            ->field('sum(a.order_price) total_price')
            ->where($where)
            ->find();
        $allTotal=0;
        if ($ordersTotal) {
        	$allTotal=$ordersTotal["total_price"];
        }
        $orders = $this->order_model
            ->alias('a')
            ->join('INNER JOIN he_member as b ON a.mid = b.id')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->field('a.*, b.username, b.nickname')
            ->where($where)
            ->order('a.pay_time desc,a.create_time desc')
            ->select();
		
		$dblTotalPrice=0.0;
        foreach($orders as $k => $v) {
            $result[$k]['str_manage'] .= '<a class="js-ajax-btn-dialog" href="' . U('Order/details', ['id' => $v['id']]) . '">订单详情</a>';
            if ($v['status'] == OrderModel::STATUS_PAY_SUCCESS) {
                $result[$k]['str_manage'] .= ' | ';
                $result[$k]['str_manage'] .= '<a data-toggle="modal" data-target="#myModal"  class="add_ext"  onclick=""   name="' . $v['id'] . '">发货</a>';
            }

            $address = json_decode($v['address'], true);
            $lists .= '<tr>
                <td>' . ($k+1) . '</td>
                <td>' . $v['order_sn'] . '</td>
                <td>' . $v['username'] . '</td>
                <td>' . $v['nickname'] . '</td>
                <td>' . $v['total_price'] . '</td>
                <td>' . $v['cut_price'] . '</td>
                <td>' . $v['order_price'] . '</td>
                <td>' . $v['freight'] . '</td>
                <td>' . $this->order_model->getUserStatusString($v['status']) . '</td>
                <td>' . $this->order_model->payTypetoString($v['pay_type']) . '</td>
                <td>' . '地址：'.$address['province'].'/'.$address['city'].'/'.$address['county'].'/'.$address['address']. '/收货人：'.$address['fullname']. '/电话：'.$address['phone'] . '</td>
                <td>' . $v['pay_time'] . '</td>
                <td>' . $v['create_time'] . '</td>
                <td>' . $result[$k]['str_manage'] . '</td>
            </tr>';
            $dblTotalPrice+=$v['order_price']*1.0;
        }
         
         $lists .= '<tr>
                <td><span style="color:red;">本页合计</span></td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td><span style="color:red;">' . sprintf("%.2f", $dblTotalPrice) . '</span></td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td></td>
            </tr>';
         $lists .= '<tr>
                <td><span style="color:red;">所有总合计</span></td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td><span style="color:red;">' . sprintf("%.2f", $allTotal) . '</span></td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td> </td>
            </tr>';
		//获取省级区域
//        $province_region = $this->agency_model->getProvincetoStr($province_code);
//        $city_region = $this->agency_model->getCitytoStr($province_code,$city_code);
//        $country_region = $this->agency_model->getCitytoStr($city_code,$country_code);
//        $this->assign('province',$province_region);
//        $this->assign('city',$city_region);
//        $this->assign('country',$country_region);
        
        $this->assign('lists', $lists);
        $this->assign('statusOption', $this->order_model->getStatusOption(I('status')));
//        $this->assign('statusOptionChoice', $this->order_model->getStatusOption());
        $this->assign('formget', I(''));
        $this->assign("Page", $page->show());
        $this->display();
    }

    /**
     * 订单详情
     */
    public function details() {
        $id = I('get.id');
        $id = intval($id);
        if (empty($id)) $this->error('empty');
        $data = $this->order_model->find($id);
        $data_member = $this->member_model->find($data['mid']);

        $data['address'] = json_decode($data['address'], true);

        $data['status_string'] = $this->order_model->getUserStatusString($data['status']);

        $order_product = $this->order_product_model
            ->alias('a')
            ->join('LEFT JOIN he_product as b ON a.pro_id = b.pro_id')
            ->where(['a.order_id' => $id])
            ->field('a.*, b.product_name')
            ->select();
        $total_price = '';
        foreach($order_product as $k => $v) {
            $every_price = $v['price'];
            $total_price += $every_price*$v['number'];
            $products .= '<tr>
                <td>' . ($k + 1) . '</td>
                <td>' . $v['product_name'] . '</td>
                <td>' . $v['price'] . '</td>
                <td>' . $v['quantity'] . '</td>
                <td>' . $v['option_name'] . '</td>
                <td>' . $v['number'] . '</td>
                <td>' . number_format($every_price*$v['number'], 2). '</td>
                ';
        }

        $this->assign('total_price', number_format($total_price, 2));
        $this->assign('products', $products);
        $this->assign('data_member', $data_member);
        $this->assign('data_order', $data);
        $this->display();
    }

    /**
     * 发货并填写运单号
     */
    public function sendNum()
    {
        $id = I('post.order_id');
        $logistics_number = I('post.logistics_number');
        $logistics_company = I('post.logistics_company');

        if (empty($id)) $this->error('empty');
        if (empty($logistics_number)) $this->error('运单号为空');
        if (empty($logistics_company)) $this->error('快递公司为空');

        $result = $this->order_model->find($id);
        if (!$result) $this->error('订单不存在');


        if ($result['status'] != OrderModel::STATUS_PAY_SUCCESS) {
            $this->error('订单未付款');
        }

        $where['id'] = $id;
        $data = [
            'logistics_number'  => $logistics_number,
            'logistics_company' => $logistics_company,
            'status'            => OrderModel::STATUS_SEND,
            'update_time'       => date('Y-m-d H:i:s'),
            'send_time'         => date('Y-m-d H:i:s'),
        ];

        $this->order_model->startTrans();
        $is_commit = true;

        $rst = $this->order_model->where($where)->save($data);
        if(!$rst) {
            $is_commit = false;
        }
        if($this->system_msg_model->addOne($result['mid'], '您的订单编号为'.$result['order_sn'].'商品已发货，请注意查看物流') == false) {
            $is_commit = false;
        }
        if($is_commit) {
            $this->order_model->commit();
            $this->success();
        } else {
            $this->order_model->rollback();
            $this->error();
        }

    }

    /**
     * 软删除
     */
    public function delete(){
        $id = I('id');
        if (empty($id)) $this->error('empty');
        if ($this->order_model->deleteOrder($id) === false) $this->error('error');
        $this->success('success');
    }

    /**
     * 设置物流
     */
    public function set_logistics()
    {
        $order_id = intval(I('order_id'));
        $logistics_number = I('post.logistics_number');
        $logistics_company = I('post.logistics_company');

        if (empty($order_id) || empty($logistics_company) || empty($logistics_number))
            $this->error('数据不能为空');

        $result = $this->order_model
            ->where(['id' => $order_id])
            ->save(['logistics_number' => $logistics_number, 'logistics_company' => $logistics_company]);

        if ($result === false) {
            $this->error('失败');
        } else {
            $this->success('成功');
        }
    }


    //导出数据方法
    public function goods_export()
    {
        $start_time = I('post.start_time');
        $end_time = I('post.end_time');
        $status = I('post.status');
        $username = I('post.username');
        $nickname=I('post.nickname');
        $order_sn = I('post.order_sn');
        $pay_timeStart=I("post.pay_timeStart");
        $pay_timeEnd=I("post.pay_timeEnd");
        $province_code = I('post.province');
        $city_code = I('post.city');
        $country_code = I('post.country');
        $hospital_name = I('post.hospital_name');
        $order_type = I('post.order_type');
        $where = [];
//        if (!$start_time && !$end_time && !$status) {
//            $this->error('请填写筛选条件');
//        }

        /*if($start_time > date('Y-m-d H:i:s')) {
            $this->error('结束时间不能与开始时间');
        }
        if($start_time > $end_time) {
            $this->error('结束时间不能与开始时间');
        }*/
        if($start_time && $end_time) {
            $where['a.create_time'] = array('between', array($start_time.' 00:00:00', $end_time.' 23:59:59'));
        }
		if ($pay_timeStart && $pay_timeEnd) {
			$where['a.pay_time'] = array('between', array($pay_timeStart.' 00:00:00', $pay_timeEnd.' 23:59:59'));
		}
		
        if($status) {
            $where['a.status'] = $status;
        }
        if($username) {
            $where['c.username'] = ['like', "%$username%"];
        }
    	if(!empty($nickname)) {
            $where['c.nickname'] = ['like', "%$nickname%"];
        }
        if($order_sn) {
            $where['a.order_sn'] = ['like', "%$order_sn%"];
        }
		if (!empty($province_code)) {
			$where['c.mem_province'] = $province_code;
		}
    	if (!empty($city_code)) {
			$where['c.mem_city'] = $city_code;
		}
    	if (!empty($country_code)) {
			$where['c.mem_country'] = $country_code;
		}
    	if (!empty($hospital_name)) {
			$where['h.hospital_name'] = ['like', "%{$hospital_name}%"];
		}
		if($order_type) {
            $where['a.order_type'] = $order_type;
        }
        //dump($where);exit;
        $row = $this->order_model
            ->alias('a')
            ->join('LEFT JOIN cmf_order_product as b ON a.id = b.order_id')
            ->join('INNER JOIN cmf_member as c ON a.mid = c.id')
            ->join('LEFT JOIN cmf_hospital as h ON a.mid = h.mid')
            ->join('LEFT JOIN cmf_product as d ON b.product_id = d.id')
            ->where($where)
            ->field('a.order_sn, a.order_price, a.create_time, a.pay_time,a.pay_type,a.address, a.freight, a.status, a.logistics_company, a.logistics_number, a.remarks, b.price, b.quantity, b.product_option, b.product_id, c.username, c.nickname,c.mem_province, c.mem_city, c.mem_country, d.product_name,h.hospital_name')
            ->order('a.pay_time desc,a.create_time desc')
            ->select();
         //dump($row);
         //exit;
        $goods_list = $row;//$goods_list;
//         dump($goods_list);exit;
        if(!$goods_list) {
            echo json_encode(['code' => '210', 'msg' => '没有数据可导出']);exit;
        }
        $data = array();
        $intTotalCount=0;
        $intTotalPrice=0;
        foreach ($goods_list as $k=>$v){
            $region = '未填写';
            if($v['mem_country']) {
            	$province = $this->region_model->where(['code' => $v['mem_province']])->getField('name');
            	$city = $this->region_model->where(['code' => $v['mem_city']])->getField('name');
            	$country = $this->region_model->where(['code' => $v['mem_country']])->getField('name');
                $region = $province.$city.$country;
            }

            $address = json_decode($v['address'], true);
            //地址修正
        	$strAddress=$address['address'];
        	$provinceName=$address['province_name'];
        	$cityName=$address['city_name'];
        	$countryName=$address['country_name'];
        	$strRegionName="";
        	if ((!empty($provinceName))&&(strpos($strAddress,$provinceName)===false)) {
        		$strRegionName.=$provinceName;
        	}
        	if ((strpos($strAddress,$cityName)===false)&&(strpos($strAddress,"市")===false)) {
        		$strRegionName.=$cityName;
        	}
        	if ((strpos($strAddress,$countryName)===false)&&(strpos($strAddress,"区")===false)&&(strpos($strAddress,"县")===false)) {
        		$strRegionName.=$countryName;
        	}
            $intTotalCount+=$v['quantity'];
            $intTotalPrice+=$v["price"]*$v["quantity"];
            $data[] = array(
                'order_sn' => $v['order_sn'],
                'username' => $v['username'],
                'nickname' => $v['nickname'],
            	'hospital_name'=>$v["hospital_name"],
                'region' => $region,
                'product_name' => $v['product_name'],// $this->product_model->where(['id' => $v['product_id']])->getField('product_name'),
                'product_option' => $v['product_option'],
                'quantity' => $v['quantity'],
                'price' => $v['price'],
            	'total_price'=>$v['quantity']*$v['price'],
                //'freight' => $v['freight'],
                'fullname' => $address['fullname'],
                'phone' => strval($address['phone']),
                'address' => $strRegionName.$address['address'],
                'postcode' => $address['postcode'],
                'create_time' => $v['create_time'],
                'pay_time' => $v['pay_time'],
                'status' => $this->order_model->getStatustoString($v['status']),
            	'pay_type'=>$this->order_model->payTypetoString($v['pay_type'])
            );
        }
		$data[] = array(
                'order_sn' => "合计",
                'username' => "",
                'nickname' => "",
				'hospital_name'=>'',
                'region' => "",
                'product_name' => "",
                'product_option' => "",
                'quantity' => $intTotalCount,
                'price' => "",
            	'total_price'=>$intTotalPrice,
                //'freight' => $v['freight'],
                'fullname' => "",
                'phone' => "",
                'address' => "",
                'postcode' => "",
                'create_time' => "",
                'pay_time' => "",
                'status' => "",
            	'pay_type'=>""
            );
//        print_r($goods_list);
//        print_r($data);exit;

        foreach ($data as $field=>$v){
            if($field == 'order_sn'){
                $headArr[]='订单编号';
            }

            if($field == 'username'){
                $headArr[]='用户名';
            }

            if($field == 'nickname'){
                $headArr[]='用户昵称';
            }
            if ($field=="hospital_name") {
            	$headArr[]='诊所名称';
            }
            
            if($field == 'region'){
                $headArr[]='用户所在区域';
            }

            if($field == 'product_name'){
                $headArr[]='商品名称';
            }
            if($field == 'product_option'){
                $headArr[]='商品规格';
            }
            if($field == 'quantity'){
                $headArr[]='商品数量';
            }

            if($field == 'price'){
                $headArr[]='商品单价';
            }
        	if($field == 'total_price'){
                $headArr[]='总价';
            }
            /*if($field == 'freight'){
                $headArr[]='运费';
            }*/

            if($field == 'fullname'){
                $headArr[]='联系人';
            }
            if($field == 'phone'){
                $headArr[]='联系电话';
            }
            if($field == 'address'){
                $headArr[]='收货地址';
            }
            if($field == 'postcode'){
                $headArr[]='邮编';
            }
            if($field == 'create_time'){
                $headArr[]='下单时间';
            }
            if($field == 'pay_time'){
                $headArr[]='付款时间';
            }
            if($field == 'status'){
                $headArr[]='订单状态';
            }
            if ($field=="pay_type") {
            	$headArr[]="支付方式";
            }
            
        }

        $filename=$start_time ? $start_time.'--'.$end_time.'_order.xls' : date('Y-m-d').'_order.xls';
//dump($filename);
        getExcel($filename,$headArr,$data);
    }


    private  function getExcel($fileName,$headArr,$data){
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //设置表头
        $key = ord("A");
        //print_r($headArr);exit;
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $key += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();

        //print_r($data);exit;
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, $value);
                /*$objActSheet->setCellValueExplicit($j.$column, $value, 
                                   PHPExcel_Cell_DataType::TYPE_STRING);*/
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//        $objWriter->save('php://output'); //文件通过浏览器下载
//        exit;
        echo json_encode(['code' => '200', 'msg' => '成功', 'url' => $this->saveExcelToLocalFile($objWriter, $fileName)]);
    }
    public function saveExcelToLocalFile($objWriter,$filename){
        // make sure you have permission to write to directory
        $filePath = $filename;
        $objWriter->save($filePath);
        return $filePath;
    }
    public function uploadInvoice(){
        $intOrderId= I('get.oid');
        $this->assign('OrderId', $intOrderId);
        $this->display();

    }
    public function saveUploadInvoice(){
        $aryResult=array();
        $aryResult["Result"]=false;
        $aryResult["Msg"]="电子票据上传失败";
        //$imgPath=upload_img("Information");

        $aryResult["path"]=$_FILES["invoiceFileName"]["name"];
        var_dump($_FILES);
        $intOrderId= I('post.hidOrderId');
        echo json_encode($aryResult);
    }

    public function refundList() {
        $where = [];

        $count = $this->refund_model
            ->alias('a')
            ->join('left join he_member as b on a.mid  = b.id')
            ->join('left join he_order as c on a.order_id = c.id')
            ->where($where)
            ->count();

        $page = $this->page($count, C("PAGE_NUMBER"));

        $result = $this->refund_model
            ->alias('a')
            ->join('left join he_member as b on a.mid  = b.id')
            ->join('left join he_order as c on a.order_id = c.id')
            ->where($where)
            ->field('a.*, b.nickname, b.username,b.phone, c.order_sn, c.order_price')
            ->limit($page->firstRow, $page->listRows)
            ->order('a.update_time desc')
            ->select();

        foreach ($result as $k => $v) {
            $result[$k]['status_string'] = $this->refund_model->statusToString($v['status']);
        }

        $para['list']       = $result;
        $para['Page']       = $page->show();
        $para['formget']    = I('');
        $this->assign($para);
        $this->display();
    }

    /**
     * @throws \Exception
     * 退款审核
     */
    public function check() {
        $refund_id= I('get.refund_id') ? : I('post.refund_id');
        $status   = I('get.status') ? : I('post.status');

        $refund_info = $this->refund_model->find($refund_id);
        $order_info = $this->order_model->find($refund_info['order_id']);
        $this->refund_model->startTrans();
        $is_commit = true;
//        dump($order_info);die;
        if($status == RefundModel::STATUS_REFUSE) {
            $content = I('post.content');
            //修改订单为原来状态
            $order_sn = $this->refund_model
                ->alias('a')
                ->where(['refund_id' => $refund_id])
                ->join('left join dr_lesson_order as b on a.lesson_order_id = b.id')
                ->getField('b.order_sn');
//            dump($order_sn);die;

            if($this->order_model->where(['order_sn' => $order_sn])->save(['status' => OrderModel::STATUS_PAY_SUCCESS]) == false) {
//                dump($this->order_model->getLastSql());die;
                $is_commit = false;$error=1;
            }
            //修改申请状态
            if($this->refund_model->where(['refund_id' => $refund_id])->save(['update_time' => getTime(), 'status' => RefundModel::STATUS_REFUSE, 'remarks' => $content]) == false) {
                $is_commit = false;$error=2;
            }


        } else if($status == RefundModel::STATUS_ACCEPT) {
            $out_refund_no = $refund_info['out_refund_no'];

            if($order_info['pay_type'] == 'wxpay') {//微信支付退款
                vendor('WxPayPubHelper.WxPayPubHelper');
                //查询订单,根据订单里边的数据进行退款

                $order_info['back_data'] = json_decode($order_info['notify_message'], true);
//                dump($order_info['back_data']);exit;
                if(!$order_info) return false;
                $order_info['order_price'] = 0.01;

                $unifiedOrder = new \Refund_pub();
                $unifiedOrder->setParameter("out_trade_no", $order_info['order_sn']);  //商户订单号
                $unifiedOrder->setParameter("total_fee", $order_info['order_price'] * 100);  //总金额
                $unifiedOrder->setParameter("refund_fee", $order_info['order_price'] * 100);  //通知地址
                $unifiedOrder->setParameter("out_refund_no", $out_refund_no);  //交易类型
//            $unifiedOrder->setParameter("transaction_id", $order_info['back_data']['transaction_id']);  //设备号
                $unifiedOrder->setParameter("op_user_id", \WxPayConf_pub::MCHID);  //设备号

//            dump($unifiedOrder);exit;

                $result = $unifiedOrder->getResult(); //退款操作
                // 这句file_put_contents是用来查看服务器返回的退款结果 测试完可以删除了
//                file_put_contents(APP_ROOT.'/Api/wxpay/logs/log3.txt',arrayToXml($result),FILE_APPEND);
//            dump($result);die;
                if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    if($this->order_model->where(['order_sn' => $order_info['order_sn']])->save(['refund_data' => json_encode($result), 'status' => OrderModel::STATUS_RETURN, 'update_time' => getTime()]) == false) {
                        $is_commit = false; $error = 1;
                    }
                } else {
                    $is_commit = false;$error = 2;
                }

            } else if($order_info['pay_type'] == 'alipay') {
                $alipay_config = C('ALIPAY_CONFIG');//dump($alipay_config);exit;

                vendor('AliWapPay.AlipayTradeRefundContentBuilder');
                vendor('AliWapPay.AlipayTradeService');
                vendor('AliWapPay.AlipayTradeWapPayContentBuilder');
                vendor('AliWapPay.AopSdk');

                $aop = new \AopClient();//dump($alipay_config);
                $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
                $aop->appId                 = $alipay_config['app_id'];
                $aop->rsaPrivateKey         = $alipay_config['merchant_private_key'];
                $aop->alipayrsaPublicKey    = $alipay_config['alipay_public_key'];
                $aop->apiVersion            = '1.0';
                $aop->signType              = 'RSA2';
                $aop->postCharset           ='UTF-8';
                $aop->format                ='json';

                $order_info['order_price'] = 0.01;//dump($aop);die;

                $request = new \AlipayTradeRefundRequest();
                $request->setBizContent( "{" .
                    "\"out_trade_no\":\"{$order_info['order_sn']}\"," .

                    "\"refund_amount\":{$order_info['order_price']}," .
                    "\"refund_reason\":\"申请退款\"," .
                    "\"out_request_no\":\"{$out_refund_no}\"" .
                    "}");
                $result = $aop->execute($request);
//                dump($request);die;


                $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;//dump($responseNode);
                if(!empty($resultCode)&&$resultCode == 10000){
                    //退款成功 可以在这里进行 修改 状态 等等一系列操作

                    if($this->order_model->where(['order_sn' => $order_info['order_sn']])->save(['refund_data' => json_encode($result), 'status' => OrderModel::STATUS_RETURN, 'update_time' => getTime()]) == false) {
                        $is_commit = false;$error =9;
                    }

                }else {
                    $is_commit = false;$error = 8;
                }
            }
            //修改申请状态
            if($this->refund_model->where(['refund_id' => $refund_id])->save(['update_time' => getTime(), 'status' => RefundModel::STATUS_ACCEPT]) == false) {
                $is_commit = false;$error = 10;
            }


        }

        if($is_commit){
            $this->refund_model->commit();
            $this->success('操作成功');
        } else {
            $this->refund_model->rollback();
            $this->error('操作失败'.$error);
        }
    }
}